package com.ruoyi.supermarket.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.supermarket.bean.CartRes;
import com.ruoyi.supermarket.domain.*;
import com.ruoyi.supermarket.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 购物车Controller
 * 
 * @author 李其伟
 * @date 2023-08-14
 */
@RestController
@RequestMapping("/supermarket/cart")
public class CartController extends BaseController
{
    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ShopService shopService;

    /**
     * 查询购物车列表
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:list')")
    @GetMapping("/list")
    public TableDataInfo list(Cart cart)
    {
        //店铺用户只能查询自己的数据
        if (hasShop()) {
            cart.setShopId(shopService.selectShopByUserId(getUserId()));
        }
        startPage();
        List<Cart> list = cartService.selectCartList(cart);
        TableDataInfo tableDataInfo =  getDataTable(list);

        List<Cart> cartList = (List<Cart>) tableDataInfo.getRows();
        if(cartList.size()==0){
            return tableDataInfo;
        }

        String[] skus = cartList.stream().map(Cart::getSku).toArray(String[]::new);
        List<Product> productList = productService.selectProductBySkus(skus);
        Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getSku, product->product));

        String[] skuCodes = cartList.stream().map(Cart::getSkuCode).toArray(String[]::new);
        List<ProductSku> productSkuList = productService.selectProductSkuBySkuCodes(skuCodes);
        Map<String, ProductSku> productSkuMap = productSkuList.stream().collect(Collectors.toMap(ProductSku::getSkuCode, productSku->productSku));

        Long[] ids = cartList.stream().map(Cart::getUserId).toArray(Long[]::new);
        List<UserInfo> userInfoList = userInfoService.selectUserInfoByIds(ids);
        Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, userInfo->userInfo));

        List<CartRes> cartResList = new ArrayList<>();
        for(Cart c : cartList){
            CartRes cr = new CartRes();
            cr.setCart(c);
            cr.setProduct(productMap.get(c.getSku()));
            cr.setProductSku(productSkuMap.get(c.getSkuCode()));
            cr.setUserInfo(userInfoMap.get(c.getUserId()));
            cartResList.add(cr);
        }
        tableDataInfo.setRows(cartResList);
        return tableDataInfo;
    }

    /**
     * 导出购物车列表
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:export')")
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Cart cart)
    {
        List<Cart> list = cartService.selectCartList(cart);
        ExcelUtil<Cart> util = new ExcelUtil<Cart>(Cart.class);
        util.exportExcel(response, list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(cartService.selectCartById(id));
    }

    /**
     * 新增购物车
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:add')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Cart cart)
    {
        return toAjax(cartService.insertCart(cart));
    }

    /**
     * 修改购物车
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:edit')")
    @Log(title = "购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Cart cart)
    {
        return toAjax(cartService.updateCart(cart));
    }

    /**
     * 删除购物车
     */
    @PreAuthorize("@ss.hasPermi('supermarket:cart:remove')")
    @Log(title = "购物车", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(cartService.deleteCartByIds(ids));
    }
}
